package com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.bean.Goods;
import com.dao.BaseDao;
import com.dao.GoodsDao;

public class GoodsDaoImpl implements GoodsDao {

	@Override
	public List<Goods> selectGoods(int pageNum, int pageSize) {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Goods> goodsList = new ArrayList<Goods>();
		String sql = "SELECT * FROM goods LIMIT ?,?";
		
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, (pageNum-1)*pageSize);
			ps.setInt(2, pageSize);
			rs = ps.executeQuery();
			System.out.println(ps);
			while(rs.next()) {
				Goods g = new Goods();
				g.setGoodsId(rs.getInt("goodsId"));
				g.setGoodsName(rs.getString("goodsName"));
				g.setGoodsFactory(rs.getString("goodsFactory"));
				g.setGoodsNum(rs.getInt("goodsNum"));
				g.setGoodsType(rs.getString("goodsType"));
				g.setGoodsPrice(rs.getDouble("goodsPrice"));
				goodsList.add(g);
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return goodsList;
	}

	@Override
	public int selectAllGoodsNum() {
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int row = 0;
		String sql = "SELECT count(*) as n FROM goods";
		
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			rs = ps.executeQuery();
			if(rs.next()) {
				row = rs.getInt("n");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return row;
	}

	@Override
	public int deleGoods(int goodsId) {
		Connection con = null;
		PreparedStatement ps = null;
		int row = 0;
		String sql = "delete from goods where goodsId = ?";
		
		try {
			con = BaseDao.getCon();
			ps = con.prepareStatement(sql);
			ps.setInt(1, goodsId);
			row = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return row;
	}

}
